/* 
 * File:   Drop.cpp
 * Author: Gab'z
 * 
 * Created on 31 mai 2012, 14:47
 */

#include "Drop.h"
#include "../../../memento/StackMemento.h"
#include "../../../Context.h"
#include "../../literal/Stack.h"

namespace calculator {

    Drop::Drop(const std::string name) : NullaryOperator(name) {
    }

    Drop::Drop(const Drop& orig) : NullaryOperator(orig._name) {
    }

    Drop::~Drop() {
    }

    Drop* Drop::clone() const {
        return new Drop(_name);
    }

    std::string Drop::isExecutable() const {
        if (Context::getInstance()->getCurrentStack()->empty()) return "Empty stack";
        return "";
    }

    const Memento* Drop::createMemento() const throw (CommandException) {
        Stack* stack = new Stack();
        const Constant* constant = Context::getInstance()->getCurrentStack()->top();
        if (constant != 0) stack->push(constant);
        return new StackMemento(clone(), stack->clone());
    }

    void Drop::restoreFromMemento(const Memento* memento) const throw (MementoException) {
        const StackMemento* stackMemento = dynamic_cast<const StackMemento*> (memento);
        if (stackMemento == 0) {
            std::string str = "Bad Memento type, expected : StackMemento, was ";
            str += typeid (*memento).name();
            throw MementoException(str);
        }
        Context::getInstance()->getCurrentStack()->push(stackMemento->_stack->top());
    }

    void Drop::eval(Stack* stack) const throw (CommandException) {
        stack->pop();
    }

}
